/*! xsApp.js
 * ================
 *
 * @Author  SoChishun
 * @Email   <14507247@qq.com>
 * @version 1.0.0
 * @license MIT <http://opensource.org/licenses/MIT>
 */

var xsApp = {};

/**
 * 弹窗对话框表单初始化
 * @param {type} options
 * @returns {undefined}
 * @version 1.0.0 <2017-3-15>
 */
xsApp.initDialogForm = function (options) {
    // 默认参数值
    var opt = {
        iframeLayerFix: true, // 是否修复弹窗尺寸
        buttonInit: true, // 是否初始化按钮控件
        inputInit: true, // 是否初始化输入控件
        beforeFn: function () {}, // 前置执行方法
        lastFn: function () {}, // 后置执行方法
    };
    if (undefined !== options) {
        $.extend(opt, options); // 参数合并
    }
    if (undefined !== opt.beforeFn) {
        opt.beforeFn(); // 执行前置方法
    }
    // 初始化操作按钮
    if (opt.buttonInit) {
        xsApp.xsfnUploadButtonInit();
    }
    // 初始化输入框
    if (opt.inputInit) {
        // see: https://github.com/smalot/bootstrap-datetimepicker
        xsApp.xsfnInitDatetimePicker('.xsui-datetimepicker');
        xsApp.xsfnInitDatetimePicker('.xsui-datepicker', {format: 'yyyy-mm-dd', pickerPosition: 'bottom-right'});
        // 设置可视化编辑器,控件不能加属性 require
        // 按钮属性查看 http://kindeditor.net/docs/option.html
        xsApp.xsfnCreateKindEditor('.xsui-editor');
        xsApp.xsfnCreateKindEditor('.xsui-pm-editor', {items: ['fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', '|', 'table', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'baidumap', '|', 'image', 'insertfile', 'link', 'unlink']});
    }
    if (undefined !== opt.afterFn) {
        opt.afterFn(); // 执行后置方法
    }

    // 配置iframe layer(放到最后面初始化，否则可能导致高度被截取 2017-3-1)
    if (opt.iframeLayerFix) {
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.iframeAuto(index); //让层自适应iframe高度
        //关闭iframe
        $('.xsui-btn-close-dialog').click(function () {
            parent.layer.close(index);
        });
    }
}

// 2017-2-13
xsApp.initDatagridPage = function (options, dgoptions) {
    var dgopt = {
        "scrollY": '50vh',
        "scrollX": true,
        "scrollCollapse": true,
        "dom": 'rt<"bottom"ip><"clear">',
        "paging": true, // 显示分页
        "lengthChange": false, // 隐藏分页尺寸选择框
        "searching": false, // 隐藏搜索
        "ordering": true, // 允许排序
        "info": true, // 显示分页信息
        "autoWidth": false, // 固定列宽
        "order": [[3, "asc"]],
        "columnDefs": [
            {"orderable": false, "targets": [0, 1, 4, 5, 6, 9, 13]}
        ],
        "language": {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        }
    }

    if (undefined !== dgoptions) {
        $.extend(dgopt, dgoptions);
    }
    $('.xsui-datagrid2').DataTable(dgopt); // 2017-2-13

    var opt = {
        checkAll: true,
        indexColumn: true,
        buttonInit: true,
        inputInit: true,
    };
    if (undefined !== options) {
        $.extend(opt, options);
    }
    if (opt.checkAll) {
        // 全选和取消全选 2017-2-21
        $('.xsui-btn-checking-all').click(function () {
            $('.xsui-datagrid tbody td :checkbox').prop('checked', $(this).prop('checked'));
        })
    }
    if (opt.indexColumn) {
        // 表格序号列
        $('.xsui-datagrid tbody tr').each(function (i) {
            $(this).children().eq(1).text(i + 1);
        })
    }
    if (opt.buttonInit) {
        xsApp.xsfnGridButtonInit();
        // 批量删除 2017-2-13
        // <button class="xsui-btn-multi-delete" data-url="delete?id=varkey" data-option='{"password":"yes","passwordMessage":"请输入口令[yes]"}'>批量删除</button>
        $('.xsui-btn-multi-delete').click(function () {
            xsApp.xsfnMultiRemove($(this));
        })
    }
    if (opt.inputInit) {
        xsApp.xsfnGridInputInit();
    }
}

// 2017-3-16
xsApp.initTreegridPage = function (options, tgoptions) {
    $('.xsui-treegrid').treegrid({treeColumn: 2});
    var opt = {
        checkAll: true,
        indexColumn: true,
        buttonInit: true,
        inputInit: true,
    };
    if (undefined !== options) {
        $.extend(opt, options);
    }
    if (opt.checkAll) {
        // 全选和取消全选 2017-2-21
        $('.xsui-btn-checking-all').click(function () {
            $('.xsui-treegrid tbody td :checkbox').prop('checked', $(this).prop('checked'));
        })
    }
    if (opt.indexColumn) {
        // 表格序号列
        $('.xsui-treegrid tbody tr').each(function (i) {
            $(this).children().eq(1).text(i + 1);
        })
    }
    if (opt.buttonInit) {
        xsApp.xsfnGridButtonInit();
        // 批量删除 2017-2-13
        // <button class="xsui-btn-multi-delete" data-url="delete?id=varkey" data-option='{"password":"yes","passwordMessage":"请输入口令[yes]"}'>批量删除</button>
        $('.xsui-btn-multi-delete').click(function () {
            xsApp.xsfnMultiRemove($(this), {gridSelector: '.xsui-treegrid'});
        })
    }
    if (opt.inputInit) {
        xsApp.xsfnGridInputInit();
    }
}
/**
 * 控制选项合并
 * <br />主要用于按钮点击事件中，合并事件方法中的默认选项与用户写在按钮中的[data-xsui-option]属性的字符串选项
 * @param {json|object} options
 * @param {string|object} soption
 * @returns {Object}
 * @version 1.0 2016-12-29
 * @since 1.1 2017-3-16 SoChishun 新增typeof识别
 * @example extend_options({a:'a1'},"{'a':'a2'}");
 */
xsApp.xsfnExtendOptions = function (options, soption) {
    if ("string" == typeof soption) {
        if (!soption || soption.indexOf(':') < 0) {
            return options;
        }
        if (soption.indexOf('}') < 0) {
            soption = '{' + soption + '}'
        }
    }
    try {
        if ("string" == typeof soption) {
            var option = new Function("return " + soption)();
        } else {
            var option = soption;
        }
        if (option) {
            $.extend(options, option);
        }
    } catch (e) {
        console.log(soption);
        console.log(e);
    }
    return options;
}

// 动态更改排序 2016-1-18
// 如：<td class="xsui-cell-sort"><input type="text" value="$vo.sort" size="3" data-value="$vo.sort" data-url="AddonU('change_sort','id='.$vo['id'].'&sort=varsort')" title="更改后,鼠标点击页面任意位置即可自动生效" /></td>
xsApp.xsfnChangeSort = function ($input) {
    var old_v = $input.data('value');
    if ($input.val() == old_v) {
        return;
    }
    $.get($input.data('url').replace('varsort', $input.val()), function (data) {
        if ('string' == typeof (data)) {
            data = JSON.parse(data);
        }
        if (data.status) {
            location.reload();
        } else {
            $('<div>' + data.info + '</div>').dialog();
        }
    })
}

/**
 * 初始化日期时间选择器
 * see: https://github.com/smalot/bootstrap-datetimepicker
 * @param {type} selector
 * @param {type} options
 * @returns {undefined}
 * @since 1.0 2017-3-15 SoChishun Added.
 * @since 1.1 2017-3-24 SoChishun 新增data-xsui-option控件参数
 */
xsApp.xsfnInitDatetimePicker = function (selector, options) {
    var opt = {
        format: 'yyyy-mm-dd hh:ii:ss',
        language: 'zh-CN',
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2, // 0:hour;1:day;2:month;3:year;4:decade
        forceParse: 1,
        weekStart: 1,
        pickerPosition: 'top-left'
    };
    if (undefined !== options) {
        $.extend(opt, options);
    }
    var option = $(selector).data('xsuiOption'); // data-xsui-option="{pickerPosition: 'bottom-left'}"
    if (option) {
        xsApp.xsfnExtendOptions(opt, option);
    }
    $(selector).datetimepicker(opt);
}
/**
 * 
 * @param {type} selector
 * @param {type} options
 * @returns {undefined}
 * @version 2017-3-15
 */
xsApp.xsfnCreateKindEditor = function (selector, options) {
    // 设置可视化编辑器,控件不能加属性 require
    if ("undefined" == typeof KindEditor || !$(selector)[0]) {
        return;
    }
    var upload_url = $(selector).data('uploadurl');
    if (undefined == upload_url) {
        console.log('KindEditor警告: [' + selector + '] 未设置上传处理页面!');
        upload_url = '';
    }
    // 按钮属性查看 http://kindeditor.net/docs/option.html
    var opt = {
        uploadJson: upload_url,
        allowFileManager: false,
        autoHeightMode: false,
        items: [
            'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', '|', 'table', 'insertorderedlist',
            'insertunorderedlist', '|', 'emoticons', 'baidumap', '|', 'image', 'insertfile', 'link', 'unlink']
    };
    if (undefined !== options) {
        $.extend(opt, options);
    }
    KindEditor.create(selector, opt);
}

/**
 * 
 * @param {type} $btn
 * @param {type} options
 * @returns {Boolean}
 * @version 2017-3-16
 */
xsApp.xsfnMultiRemove = function ($btn, options) {
    var opt = {
        url: $btn.attr('href') ? $btn.attr('href') : $btn.data('url'),
        gridSelector: '.xsui-datagrid',
        password: '',
        passwordMessage: '请输入口令:',
    };
    var isConfirm = false; // 是否已经弹出确认框了
    // 控制选项
    if (options) {
        $.extend(opt, options);
    }
    var option = $btn.data('option');
    if (option) {
        xsApp.xsfnExtendOptions(opt, option);
    }
    if (!opt.url) {
        alert('[xsfnMultiRemove]URL无效!');
        return false;
    }
    if (opt.password) { // 口令确认框 2017-3-16
        var pmpt = prompt(opt.passwordMessage);
        if (!pmpt) {
            return false;
        }
        if (pmpt != opt.password) {
            alert('口令错误!');
            return false;
        }
        isConfirm = true;
    }
    var ids = '';
    var n = 0;
    $(opt.gridSelector + ' tbody tr :checkbox:checked').each(function () {
        if (ids) {
            ids += ',';
        }
        ids += $(this).val();
        n++;
    });
    if (n < 1) {
        alert('没有选中任何行!');
        return false;
    }
    if (!isConfirm && !confirm('您确定要删除选中的 ' + n + ' 条记录吗?')) {
        return false;
    }
    $.get(opt.url.replace('varkey', ids), {}, function (data) {
        if (data.status) {
            location.reload();
        } else {
            layer.alert(data.info, {icon: 5, offset: [160, 0]});
        }
    })
    return false;
}
// 2017-3-16
xsApp.xsfnSingleRemove = function ($btn) {
    if (!confirm('您确定要删除该记录吗?')) {
        return false;
    }
    var url = $btn.attr('href') ? $btn.attr('href') : $btn.data('url');
    $.get(url, {}, function (data) {
        if (data.status) {
            location.reload();
        } else {
            layer.alert(data.info, {icon: 5, offset: [160, 0]});
        }
    })
}
/**
 * 
 * @param {type} $btn
 * @param {type} gridChecked
 * @returns {Boolean}
 * @since 1.0 2017-3-16
 * @since 1.1 2017-3-18 新增gridChecked参数
 */
xsApp.xsfnDialogForm = function ($btn, gridChecked) {
    var url = $btn.attr('href') ? $btn.attr('href') : $btn.data('url');
    if (!url) {
        alert('URL无效!');
        return false;
    }
    if (gridChecked) {
        var btnopt = {gridSelector: '.xsui-datagrid'};
        var ids = '';
        var n = 0;
        $(btnopt.gridSelector + ' tbody tr :checkbox:checked').each(function () {
            if (ids) {
                ids += ',';
            }
            ids += $(this).val();
            n++;
        });
        if (n < 1) {
            alert('没有选中任何行!');
            return false;
        }
        url = url.replace('varkey', ids);
    }
    var title = $btn.attr('title') ? $btn.attr('title') : $btn.text();
    var options = {width: 768, height: 520};
    var soption = $btn.data('xsuiOption'); // 控件的[data-xsui-option]属性自定义选项：<a data-xsui-option="{'key':'value'}" />
    if (soption) {
        options = xsfn_extend_options(options, soption);
    }
    //iframe窗
    layer.open({
        type: 2,
        title: title,
        closeBtn: 1, //不显示关闭按钮
        shade: [0],
        //area: [options.width + 'px', options.height + 'px'],
        area: ['50vw', '50vh'],
        //offset: 'rb', //右下角弹出
        //time: 2000, //2秒后自动关闭
        maxmin: true, //开启最大化最小化按钮
        offset: [160, 0],
        anim: 2,
        content: [url, 'no'], //iframe的url，no代表不显示滚动条
    });
}
// 2017-3-17
xsApp.xsfnGridInputInit = function () {
    // 状态单元格切换开关控制 2016-1-18 SoChishun Added.
    // 如：<td class="xsui-cell-status"><a href="AddonU('change_status','id='.$vo['id'].'&status=varstatus')" title="点击隐藏" data-value="$vo.status" class="xsui-success"><i class="fa fa-check fa-fw"></i></a></td>
    if ('undefined' !== typeof ($.fn.togglelink)) {
        $('td.xsui-cell-status a').togglelink();
    }
    // 动态更改排序 2015-10-24 SoChishun Added.
    $('td.xsui-cell-sort input').blur(function () {
        var $input = $(this);
        xsApp.xsfnChangeSort($input);
    })
}
// 2017-3-17
xsApp.xsfnGridButtonInit = function () {

    $('.xsui-btn-refresh').click(function () {
        location.reload();
        return false;
    })
    // 2017-2-21
    $('.xsui-btn-delete').click(function () {
        xsApp.xsfnSingleRemove($(this));
        return false;
    })
    // 新增 2017-2-14
    $('.xsui-btn-add-dialog, .xsui-btn-edit-dialog').click(function () {
        xsApp.xsfnDialogForm($(this));
        return false;
    })
    // 快速批量编辑 2017-3-18
    $('.xsui-btn-multi-edit-dialog').click(function () {
        xsApp.xsfnDialogForm($(this), true);
        return false;
    })
}
// 2017-3-24
xsApp.xsfnUploadButtonInit = function () {
    // 上传图片按钮
    $('.xsui-btn-singlefile-uploader-image').click(function () {
        var $btn = $(this);
        var url = $btn.attr('href') ? $btn.attr('href') : $btn.data('url');
        if (!url) {
            alert('URL无效!');
            return false;
        }
        var title = $btn.attr('title') ? $btn.attr('title') : $btn.text();
        //iframe窗
        layer.open({
            type: 2,
            title: title,
            closeBtn: 1, //不显示关闭按钮
            shade: [0],
            //area: [options.width + 'px', options.height + 'px'],
            area: ['50vw', '50vh'],
            //offset: 'rb', //右下角弹出
            //time: 2000, //2秒后自动关闭
            maxmin: true, //开启最大化最小化按钮
            offset: [160, 0],
            anim: 2,
            content: [url, 'no'], //iframe的url，no代表不显示滚动条
        });
        return false;
    })
    // 删除图片按钮
    $('.xsui-btn-singlefile-delete-image').click(function () {
        var $btn = $(this);
        var path = $btn.parent().prev().val();
        if ('' == path) {
            return false;
        }
        if (!confirm('您确定要删除该图片吗?')) {
            return false;
        }
        var url = $btn.attr('href') ? $btn.attr('href') : $btn.data('url');
        $.post(url, {filepath: path}, function (data) {
            if (data.success) {
                $btn.parent().prev().val('');
            } else {
                layer.alert(data.info, {icon: 5, offset: [160, 0]});
            }
        })
        return false;
    })
}
/**
 * 颜色选择器初始化
 * @returns {undefined}
 * @version 1.0 2017-3-27
 */
xsApp.xsfnColorPickerInputInit = function () {
    $('.xsui-color-picker').colorpicker({
        colorSelectors: {
            'black': '#000000',
            'white': '#ffffff',
            'red': '#FF0000',
            'default': '#777777',
            'primary': '#337ab7',
            'success': '#5cb85c',
            'info': '#5bc0de',
            'warning': '#f0ad4e',
            'danger': '#d9534f'
        }
    });
}
/**
 * 显示隐藏密码 
 * @param {type} option
 * @returns {undefined}
 * @version 1.0 2017-3-15 SoChishun Added.
 */
xsApp.xsfnTogglePassword = function (option) {
    var opt = {selector: '.xsui-btn-show-password', name: 'password', placeholder: '密码'};
    if (option) {
        $.extend(opt, option);
    }
    $(opt.selector).mousedown(function () {
        var $this = $(this);
        var value = $this.parent().prev().find('input').val();
        if (value) {
            $this.parent().prev().html('<input type="text" name="' + opt.name + '" class="form-control input-sm" placeholder="' + opt.placeholder + '" required="required" value="' + value + '" />');
        }
    }).mouseup(function () {
        var $this = $(this);
        var value = $this.parent().prev().find('input').val();
        if (value) {
            $this.parent().prev().html('<input type="password" name="' + opt.name + '" class="form-control input-sm" placeholder="' + opt.placeholder + '" required="required" value="' + value + '" />');
        }
    })
}